#pragma once
#include <asio.hpp>
#include <functional>
#include <memory>
#include <chrono>

class TimerWrapper : public std::enable_shared_from_this<TimerWrapper> {
public:
    TimerWrapper(asio::io_context& io)
        : timer_(io) {}

    // 循环定时器，回调返回 bool 控制循环
    template <typename F>
    void start(std::chrono::milliseconds interval, F&& cb, bool first_immediate = false) {
        interval_ = interval;
        callback_ = std::forward<F>(cb);

        if (first_immediate) {
            if (!callback_()) return;  // 第一次立即触发，返回 false 停止
        }

        schedule_next();
    }

    template <typename F>
    void start_once(std::chrono::milliseconds interval, F&& cb) {
        auto self = shared_from_this();
        auto callback = std::forward<F>(cb); // 先移动/拷贝到局部变量，保证生命周期

        timer_.expires_after(interval);
        timer_.async_wait([self, callback = std::move(callback)](const asio::error_code& ec){
            if (!ec) callback();
        });
    }

    void stop() {
        timer_.cancel();
    }

private:
    void schedule_next() {
        timer_.expires_after(interval_);
        auto self = shared_from_this();
        timer_.async_wait([self](const asio::error_code& ec){
            if (!ec) {
                if (self->callback_()) self->schedule_next();
            }
        });
    }

private:
    asio::steady_timer timer_;
    std::chrono::milliseconds interval_;
    std::function<bool()> callback_; // 内部统一存储
};

